# -*- coding:utf-8 -*-
# Create your views here.
from django.conf import settings
from django.http import HttpResponseRedirect
from django.template import  Template
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext

from pp_case.forms  import InvestigateForm,PPCaseHandleForm,CooperateForm,EndCaseForm,SettledCooperateForm
from pp_case.models import PPCaseInfo,PPCaseInvestigation,PPCaseHandle,Cooperate,CaseResult

from django.core.mail import send_mail
import datetime

def dashboard(request):
    """
    Don't get the user's information right now , todo
    """
    initiated_pp_case = PPCaseInfo.objects.filter(
        processStatus = 0,
    )
    updated_pp_case = PPCaseInfo.objects.filter(
        isPayPalUpdate = True,
    )
    title = 'PP投诉'

    return render_to_response('dashboard.html',
        RequestContext(request,
                       {
                        'title':title,
                        'initiated_pp_case':initiated_pp_case,
                        'updated_pp_case':updated_pp_case,
                       }
                       )
    )
def case_wait_response(request):
    """
    Don't get the user's information right now , todo
    """

    wait_pp_case = PPCaseInfo.objects.filter(
        cooperate__settledDate__isnull = True,
        cooperate__deadline__gte = datetime.datetime.now()
    )

    title = 'PP投诉'

    return render_to_response('case_wait_response.html',
        RequestContext(request,
                       {
                        'title':title,
                        'pp_case':wait_pp_case,
                       }
                       )
    )

@login_required()
def view_pp_case(request, pp_case_id):
    pp_case = get_object_or_404(PPCaseInfo,pk=pp_case_id)
    try :
        caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    except  PPCaseInvestigation.DoesNotExist:
        caseInvInfo = None

    try :
        caseHandleInfo = PPCaseHandle.objects.filter(caseID=pp_case)
    except PPCaseHandle.DoesNotExist:
        caseHandleInfo = None
    return render_to_response('pp_case_detail.html',
                              RequestContext(request,
                                        {
                                      'pp_case':pp_case,
                                        'case_investigate':caseInvInfo,
                                        'case_handles':caseHandleInfo,
                                        },
        )
)

@login_required()
def pp_case_investigate(request,pp_case_id):
    # find that pp_case_info model
    pp_case = get_object_or_404(PPCaseInfo,pk=pp_case_id)
    #sometime i need to refresh it
    try :
        caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    except  PPCaseInvestigation.DoesNotExist :
        caseInvInfo = PPCaseInvestigation( orderNo=pp_case )
        caseInvInfo.save()
    # use the previous  data to fill the form
    form_investigate_pp_case = InvestigateForm( instance=caseInvInfo )


    if request.method == 'GET':
        return render_to_response('pp_case_investigate.html',
             RequestContext(request,{
            'investigate_form':form_investigate_pp_case,
            'pp_case':pp_case,
            }),
        )
    else:
        form = InvestigateForm(request.POST)
        if form.is_valid():
            caseInvInfo.departmentGroup = form.cleaned_data.get('departmentGroup' )
            caseInvInfo.investigationInfo = form.cleaned_data.get('investigationInfo' , '')
            caseInvInfo.reasonGroup = form.cleaned_data.get('reasonGroup' , '')
            caseInvInfo.involvedProvider = form.cleaned_data.get('involvedProvider' , '')
            caseInvInfo.involvedCategory = form.cleaned_data.get('involvedCategory' , '')
            caseInvInfo.save(force_update=True)
            # need to update the PayPal case process status if the processsStatus == 0
            if not pp_case.processStatus:
                pp_case.processStatus = 1
                #    ON_VESTIGATION = 1
                pp_case.save()
                #return to PayPal case detail site
            return HttpResponseRedirect( pp_case.get_absolute_url() )
        else:
            return render_to_response('error.html',
                    {'error_information' : form.errors
                },
            )
                       

@login_required()
def pp_case_handle(request , pp_case_id):
    pp_case = get_object_or_404(PPCaseInfo,pk=pp_case_id)
    # you can only make a handle after an investigation
    if not pp_case.processStatus:
        return render_to_response('error.html',
            {'error_information' : '此事件还没填写调查情况'
             },
        )

    caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    caseHandle = PPCaseHandle( caseID = pp_case )

    if request.method == 'GET':
        form_CaseHandle = PPCaseHandleForm( instance=caseHandle )
        return render_to_response('pp_case_handle.html',
            RequestContext(request,{
                'handle_form':form_CaseHandle,
                'pp_case':pp_case,
                'case_investigate':caseInvInfo,
            }),
        )
    else:
        form = PPCaseHandleForm(request.POST,instance=caseHandle)
        if form.is_valid():
            form.save()
            caseHandle.save()
            #处理结束
            pp_case.processStatus = 3
            #更新信息
            pp_case.isPayPalUpdate = False
            pp_case.save()
                #return to PayPal case detail site
            return HttpResponseRedirect( pp_case.get_absolute_url() )

@login_required()
def pp_case_cooperate(request, pp_case_id):
    pp_case = get_object_or_404(PPCaseInfo,pk = pp_case_id)
    # you can only make a handle after an investigation
    if not pp_case.processStatus:
        return render_to_response('error.html',
            {'error_information' : '此事件还没填写调查情况'
             },
        )
    caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    # 需要在收到同事回应的时候反馈处理效果
    #所以要先查询表，这样就一个case只能联系一次
    try :
        pp_case_coo = Cooperate.objects.get( caseID=pp_case )
    except Cooperate.DoesNotExist:
        pp_case_coo = Cooperate(caseID = pp_case)
    if request.method =='GET':
        form_pp_case_coo = CooperateForm(instance = pp_case_coo)
        return render_to_response('pp_case_cooperate.html',
            RequestContext(request,{
                'cooperate_form':form_pp_case_coo,
                'pp_case':pp_case,
                'case_investigate':caseInvInfo,
            }),
        )
    else:
        form = CooperateForm(request.POST,instance=pp_case_coo)
        if form.is_valid():
            form.save()
            pp_case.processStatus = 1
            pp_case.save()
            # there is no need to send Email if the case got solution from colleagues
            if  not pp_case_coo.repliedSolution:
                #send_mail('测试','django 测试','liuchuqiao@milanoo.cn',['liuchuqiao@milanoo.com'])
                str1 = unicode('投诉协助请求','utf8')
                str2 = unicode('要求回复时间','utf8')
                str3 = unicode('事件描述','utf8')
                str4 = unicode('期望效果','utf8')
                subject =':'.join([str1,pp_case.orderNo])
                content1 = ':\n'.join([str2,str(pp_case_coo.deadline)])
                content2 = ':\n'.join([str3,caseInvInfo.investigationInfo])
                content3 = ':\n'.join([str4,pp_case_coo.expectSolution])
                content = '\n-----------------------------------------------------\n'.join([content1,content2,content3])
                send_mail(subject,content,'paypal@milanoo.cn',[pp_case_coo.requestStaff],fail_silently=False)
        #return to PayPal case detail site
            return HttpResponseRedirect( pp_case.get_absolute_url() )
        else:
            return render_to_response('error.html',
                    {'error_information' : form.errors
                },
                                      )
def pp_case_endcase(request,pp_case_id):
    pp_case = get_object_or_404(PPCaseInfo,pk=pp_case_id)
    # you can only make a handle after an investigation
    if not pp_case.processStatus:
        return render_to_response('error.html',
            {'error_information' : '此事件还没填写调查情况'
             },
        )
    try:
        caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    except PPCaseInvestigation.DoesNotExist:
        return HttpResponseRedirect('%sinvestigate/'%pp_case.get_absolute_url())
    try :
        pp_case_result = CaseResult.objects.get( caseID=pp_case )
    except CaseResult.DoesNotExist:
        pp_case_result = CaseResult(caseID = pp_case)
    
    if request.method == 'GET':
        form_result = EndCaseForm( instance=pp_case_result )
        return render_to_response('pp_case_endcase.html',
            RequestContext(request,{
                'endform':form_result,
                'pp_case':pp_case,
                'case_investigate':caseInvInfo,
            }),
        )
    else:
        pp_case_result.endDate = pp_case.paypalRefreshDate
        form_result = EndCaseForm(request.POST,instance=pp_case_result)
        if form_result.is_valid():
            pp_case.isPayPalUpdate = False
            pp_case.save()
            form_result.save()
            return HttpResponseRedirect( '/pp_case/dashboard/' )
        else:
            return render_to_response('error.html',
                    {'error_information' : form_result.errors
                },
            )

@login_required()
def pp_case_settled_cooperate(request,pp_case_id):
    pp_case = get_object_or_404(PPCaseInfo,pk=pp_case_id)
    caseInvInfo = PPCaseInvestigation.objects.get(orderNo=pp_case)
    try:
        settled_cooperate = Cooperate.objects.get(caseID = pp_case)
    except Cooperate.DoesNotExist :
        return render_to_response('error.html',
                    {'error_information' : '此事件没有联系同事的记录'
                },
                                  )
    #相同的modle渲染不同的form
    if request.method == 'GET':
        form_settled_cooperate = SettledCooperateForm(instance=settled_cooperate)
        return render_to_response(
            'pp_case_endCooperate.html',
            RequestContext(request,{
                'form_settled_cooperate':form_settled_cooperate,
                'pp_case':pp_case,
                'case_investigate':caseInvInfo,
                'cooperate':settled_cooperate,
            }
            )
        )
    else:
        form_settled_cooperate = SettledCooperateForm(request.POST,instance=settled_cooperate)
        if form_settled_cooperate.is_valid():
            form_settled_cooperate.save()
            return HttpResponseRedirect('/'.join(['/pp_case',pp_case.caseID,'handle']))
        else:
            return render_to_response('error.html',
                    {'error_information' : form_settled_cooperate.errors
                },
            )
